﻿package nl.joeyvandijk
{
	import flash.display.Sprite;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.IEventDispatcher;
	
	public class Data extends Sprite
	{
		private var dataLoader:URLLoader;
		private var dataURL:String = '';
		public var items:Array;
		
		public function Data (){}
		
		public function load(input:String)
		{
			dataURL = input;
			
			init();
		}
			
		
		private function init():void
		{
			dataLoader = new URLLoader();
            configureListeners(dataLoader);

            try {
                dataLoader.load(new URLRequest(dataURL));
            } catch (error:Error) {
                trace("ERROR: Unable to load requested document.");
            }
		}
		
		private function configureListeners(dispatcher:IEventDispatcher):void {
            dispatcher.addEventListener(Event.COMPLETE, completeHandler);
            dispatcher.addEventListener(Event.OPEN, openHandler);
            dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        }

        private function completeHandler(e:Event):void {
			items = new Array();
			for each(var p:XML in XML(dataLoader.data)..photo)
			{
				var obj:Object = new Object();
				obj.url = p.@url;
				obj.time = p.@time;
				obj.text = p.@text;
				obj.textxy = p.@xy;
				obj.logoxy = p.@logoxy;
				obj.logo = p.@logo;
				obj.link = p.@link;
				items.push(obj);
			}
			dispatchEvent(new Event(Event.COMPLETE));
        }

        private function openHandler(event:Event):void {
            trace("openHandler: " + event);
        }

        private function progressHandler(event:ProgressEvent):void {
            trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
        }

        private function securityErrorHandler(event:SecurityErrorEvent):void {
            trace("securityErrorHandler: " + event);
        }

        private function httpStatusHandler(event:HTTPStatusEvent):void {
            trace("httpStatusHandler: " + event);
        }

        private function ioErrorHandler(event:IOErrorEvent):void {
            trace("ioErrorHandler: " + event);
        }

	}
}	